import { Suspense } from 'react';
import { Navigate, useRoutes } from 'react-router-dom';

import Login from '@/pages/login';
import Home from '@/pages/home';
import GoutConsultation from '@/pages/gout-consultation';
import DemonstrationBase from '@/pages/demonstration-base';
import MedicalAlliance from '@/pages/medical-alliance';
import MedicalTraining from '@/pages/medical-training';


export interface RouterBody {
  name?: string,
  path: string,
  component?: any,
  element?: any,
  auth?: (number | string)[];
  children?: Array<RouterBody>,
};

const routes: Array<RouterBody> = [
  {
    path: '/',
    component: Home,
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/goutConsultation',
    auth: [2],
    component: GoutConsultation,
  },
  {
    path: '/demonstrationBase',
    auth: [1, 2],
    component: DemonstrationBase,
  },
  {
    path: '/medicalAlliance',
    auth: [1, 2],
    component: MedicalAlliance,
  },
  {
    path: '/medicalTraining',
    auth: [1, 2],
    component: MedicalTraining,
  },
  {
    path: '/404',
    component: () => <div>用户暂无权限访问</div>,
  },
  {
    path: '*',
    component: () => <div>页面不存在</div>,
  },
];

const changeRouter = (routes: Array<RouterBody>): any => {
  const userType = localStorage.getItem('User_Type') ?? 1;

  return routes.map(item => {
    if (item.children) {
      item.children = changeRouter(item.children);
    }

    if (
      item.path !== '/404' &&
      item.auth !== undefined &&
      item.auth.find((permission) => permission === userType) === undefined
    ) {
      item.element = <Navigate replace to="/404"></Navigate>;
    } else {
      item.element = <Suspense fallback={<div>加载中...</div>}>
        <item.component />
      </Suspense>;
    }
    return item;
  });
}

function RouteElement() {
  const element = useRoutes(changeRouter(routes));
  return element;
}

export default RouteElement;
